package com.slipper.system.handler;

import javax.servlet.http.HttpServletResponse;

import com.slipper.common.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.slipper.common.util.ResultUtil;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler
    public String exceptionHandler(HttpServletResponse response, Exception e) {
        Throwable throwable = e;
        if (throwable != null) {
            throwable = e.getCause() != null ? e.getCause() : e;
            response.setStatus(HttpServletResponse.SC_OK);
        }
        
        String errCode = "0";
        String errMsg;
        if (throwable instanceof CommonException) {
            CommonException CommonException = (CommonException) throwable;
            errCode = CommonException.getCode();
            errMsg = CommonException.getMessage();
        } else if (e != null && e.getMessage() != null && e.getMessage().indexOf("Dao.xml") > 0) {
            errMsg = "输入参数出错，请核查！";
        } else {
            errMsg = throwable == null || throwable.getMessage() == null ? "未知错误！" : throwable.getMessage();
            if (errMsg != null && errMsg.contains("Dao.xml")) {
                errMsg = "输入参数出错，请核查！";
            }
        }
        
        logger.error("调用发生异常！", e);
        return ResultUtil.failureResult(errCode, errMsg).toString();
    }
}